package com.pig.openg1.data;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLUtils;
import android.opengl.Matrix;
import android.util.Log;

import com.pig.openg1.R;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

public class TextureData {

    private final String TAG = TextureData.class.getSimpleName();
    private Context mContext;
    public static float[] mProjMatrix = new float[16]; //投影矩阵
    public static float[] mVMatrix = new float[16]; //摄像机位置矩阵
    public static float[] mMVPMatrix = new float[16];// 总变化矩阵
    public static float[] mMMatrix = new float[16];// 变换矩阵

    private int mProgram,aPosition,aTexCoor,uMVPMatrix,textureID;

    private FloatBuffer mVerBuffer, mTexCoorBuffer;

    public TextureData(Context context)
    {
        this.mContext = context;
        //初始化数据
        float[] vers = new float[]{
            1f,1f,0f,
            1f,-1f,0,
            -1f,-1f,0,
            -1f,1f,0,
            0,0,4f
        };

        mVerBuffer = getFloatBuffer(vers);
        //纹理数据
        float color[] = new float[]{
                0.5F, 0F,
                -0.5F, 1.5f,
                1.5f, 1.5f,
                -0.5F, 1.5f,
                1.5f, 1.5f

        };
        mTexCoorBuffer = getFloatBuffer(color);
        //加载片元
        mProgram = GLES20.glCreateProgram();
        if(mProgram!= GLES20.GL_FALSE)
        {
            String mVertexSource = loadFile("Texure_vertex.glsl");
            String mFragSource = loadFile("Texure_frag.glsl");
            int mVertexShader = loadShader(GLES20.GL_VERTEX_SHADER,mVertexSource);
            int mFragShader = loadShader(GLES20.GL_FRAGMENT_SHADER,mFragSource);

            GLES20.glAttachShader(mProgram,mVertexShader);
            GLES20.glAttachShader(mProgram,mFragShader);

            GLES20.glLinkProgram(mProgram);
            int[] complied = new int[1];
            GLES20.glGetProgramiv(mProgram,GLES20.GL_LINK_STATUS,complied,0);
            if(complied[0] == GLES20.GL_FALSE)
            {
                Log.e(TAG,GLES20.glGetProgramInfoLog(mProgram));
                GLES20.glDeleteProgram(mProgram);
                mProgram = 0;
            }
        }

        //如果片元加载成功，获取片元的的参数
        aPosition = GLES20.glGetAttribLocation(mProgram,"aPosition");
        aTexCoor = GLES20.glGetAttribLocation(mProgram,"aTexCoor");
        uMVPMatrix = GLES20.glGetUniformLocation(mProgram,"uMVPMatrix");

    }

    public void drawSelf() {

        GLES20.glUseProgram(mProgram);
        //开始位移操作
        Matrix.setRotateM(mMMatrix, 0, 0, 0, 0, 1);
        Matrix.translateM(mMMatrix, 0, 1, 0, 0);
        Matrix.translateM(mMMatrix, 0, 0, 1, 0);
        Matrix.translateM(mMMatrix, 0, 0, 0, 1);
        //给着色器添加颜色
        GLES20.glUniformMatrix4fv(uMVPMatrix,1,false,getFinalMatrix(),0);
        //顶点
        GLES20.glVertexAttribPointer(aPosition,3,GLES20.GL_FLOAT,false,0,mVerBuffer);
        //纹理坐标
        GLES20.glVertexAttribPointer(aTexCoor,2,GLES20.GL_FLOAT,false,0,mTexCoorBuffer);
        //开启顶点和纹理绘制
        GLES20.glEnableVertexAttribArray(aPosition);
        GLES20.glEnableVertexAttribArray(aTexCoor);

        //绑定纹理
        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,textureID);

        //绘制
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN,0,5);

//        GLES20.glDisableVertexAttribArray(aPosition);
//        GLES20.glDisableVertexAttribArray(aTexCoor);

    }

    /***
     * 创建纹理
     */
    public void initTexture()
    {
        //生成纹理的ID
        int texture[] = new int[1];
        //创建一个纹理
        GLES20.glGenTextures(1,texture,0);
        textureID = texture[0];
        //绑定纹理
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,textureID);
        //过滤器
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
                GLES20.GL_TEXTURE_MIN_FILTER,  //指定缩小过滤的方法
                GLES20.GL_NEAREST); // 最临近的过滤
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
                GLES20.GL_TEXTURE_MAG_FILTER, //指定放大过滤波的方法
                GLES20.GL_LINEAR); //线性插值
        //纹理使用方式
//        GLES20.glTexParameterf(要操作的纹理类型，环绕方向，环绕参数);
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
                GLES20.GL_TEXTURE_WRAP_S,
                GLES20.GL_REPEAT);
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
                GLES20.GL_TEXTURE_WRAP_T,
                GLES20.GL_REPEAT);

        //加载图片
        try {
            @SuppressLint("ResourceType")
            InputStream in = mContext.getResources().openRawResource(R.mipmap.wall);
            Bitmap mBitmap = BitmapFactory.decodeStream(in);
            in.close();
            //纹理类型，纹理层次，纹理图片，纹理的边框尺寸
            GLUtils.texImage2D(GLES20.GL_TEXTURE_2D,0,mBitmap,0);
            mBitmap.recycle();//释放内存
        }catch(Exception e)
        {
            Log.e(TAG,e.getMessage());
        }

    }


    public static float[] getFinalMatrix()
    {
        Matrix.multiplyMM(mMVPMatrix,0,mVMatrix,0,mMMatrix,0);
        Matrix.multiplyMM(mMVPMatrix,0,mProjMatrix,0,mMVPMatrix,0);
        return mMVPMatrix;
    }


    private FloatBuffer getFloatBuffer(float[] buffer)
    {
        ByteBuffer mByteBUffer = ByteBuffer.allocateDirect(buffer.length * 4);
        mByteBUffer.order(ByteOrder.nativeOrder());
        FloatBuffer mFloatBuffer = mByteBUffer.asFloatBuffer();
        mFloatBuffer.put(buffer);
        mFloatBuffer.position(0);
        return mFloatBuffer;
    }

    private ShortBuffer getShortBuffer(short[] buffer)
    {
        ByteBuffer mByteBuffer = ByteBuffer.allocateDirect(buffer.length * 2);
        mByteBuffer.order(ByteOrder.nativeOrder());
        ShortBuffer mShortBuffer = mByteBuffer.asShortBuffer();
        mShortBuffer.put(buffer);
        mShortBuffer.position(0);
        return mShortBuffer;
    }

    private String loadFile(String path)
    {
        String result = null;
        try{
            InputStream in = mContext.getAssets().open(path);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int lenght = 0;
            byte[] buffer = new byte[1024];
            while((lenght = in.read(buffer)) > 0 )
            {
                out.write(buffer,0,lenght);
            }
            result = out.toString();
            in.close();
            out.close();
        }catch(Exception e)
        {
            Log.e(TAG,e.getMessage());
            return result;
        }
        return result;
    }

    private int loadShader(int type,String source)
    {
        int shader = GLES20.glCreateShader(type);
        if(shader != GLES20.GL_TRUE)
        {
            GLES20.glShaderSource(shader,source);
            GLES20.glCompileShader(shader);
            int[] complied = new int[1];
            GLES20.glGetShaderiv(shader,GLES20.GL_COMPILE_STATUS,complied,0);
            if(complied[0] != GLES20.GL_TRUE)
            {
                Log.e(TAG,GLES20.glGetShaderInfoLog(shader));
                GLES20.glDeleteShader(shader);
                shader = 0;
            }
        }
        return shader;

    }

    private String loadFile(Context mContext,String path)
    {
        String result = null;
        try{
            InputStream in = mContext.getAssets().open(path);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int lenght = 0 ;
            byte[] buffer = new byte[1024];
            while ( (lenght = in.read(buffer))> 0 )
            {
                out.write(buffer,0,lenght);
            }
            result = out.toString();
            in.close();
            out.close();
        }catch(Exception e)
        {
            Log.e(TAG,e.getMessage());
            return result;
        }
        return result;
    }


}
